import { $get } from './api'

export const initMenu = (router, store) => {
  if (store.state.routes.length > 0) {
    return
  }

  $get('permission/menu').then((res) => {
    console.log(res)
    if (res.code == 200 && res.data) {
      //格式化Router
      let fmtRoutes = formatRoutes(res.data)
      //添加到router
      router.addRoutes(fmtRoutes)
      //将数据存入vuex
      store.commit('initRoutes', fmtRoutes)
    }
  })
}

export const formatRoutes = (routes) => {
  let fmtRoutes = []
  routes.forEach(router => {
    let { path, component, name, icon, children } = router
    if (children && children instanceof Array) {
      //递归
      children = formatRoutes(children)
    }
    let fmtRouter = {
      path: path, name: name, icon: icon, children: children,
      component(resolve) {
        if (component.startsWith('Home')) {
          require(['../views/' + component + '.vue'], resolve)
        } else if (component.startsWith('Re')) {
          require(['../views/recruit/' + component + '.vue'], resolve)
        } else if (component.startsWith('Sys')) {
          require(['../views/sys/' + component + '.vue'], resolve)
        } else if (component.startsWith('Monitor')) {
          require(['../views/monitor/' + component + '.vue'], resolve)
        } else if (component.startsWith('T')) {
          require(['../views/tool/' + component + '.vue'], resolve)
        }
      }
    }
    fmtRoutes.push(fmtRouter)
  })
  return fmtRoutes
}